/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package be.vdab.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author tom.vanpoucke
 */
public class AbstractDAO {
    private static final String JNDI_NAME = "java:/comp/env/jdbc/cultuurhuis";
    public Connection getConnection(){
        Context context = null;
        try{
            context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup(JNDI_NAME);
            return dataSource.getConnection();
        }
        catch(NamingException ex){
            throw new DAOException(JNDI_NAME + " niet gevonden", ex);
        }
        catch(SQLException ex){
            throw new DAOException("Kan geen connectie krijgen van " + JNDI_NAME, ex);
        }
        finally{
            try{
                if(context != null){
                    context.close();
                }
            }
            catch(NamingException ex){
                throw new DAOException("Kan " + JNDI_NAME + " niet sluiten", ex);
            }
        }
    }
    public void close(Statement statement, Connection connection){
        if(statement != null){
            try{
                statement.close();
            }
            catch(SQLException ex){
                throw new DAOException("Kan statement niet sluiten", ex);
            }
        }
        if(connection != null){
            try{
                connection.close();
            }
            catch(SQLException ex){
                throw new DAOException("Kan connectie niet sluiten", ex);
            }
        }           
    }
    public void close(ResultSet resultSet, Statement statement, Connection connection){
        if(resultSet != null){
            try{
                resultSet.close();
            }
            catch(SQLException ex){
                throw new DAOException("Kan resultset niet sluiten", ex);
            }
            close(statement,connection);
        }
    }
}
